import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, Clipboard, TextInput } from 'react-native';
import { Container, Content, View, Toast, Text, Icon } from 'native-base';
import { Avatar } from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import AsyncStorage from '@react-native-community/async-storage';
import { connect } from 'react-redux';

import { Header, Loading } from '../../component';
import { Colors, Metrics } from '../../theme';
import Http from '../../utils/HttpPost';
import ParamsValidate from '../../utils/ValueValidate';


class Login extends Component {
	constructor(props) {
		super(props);
		this.state = {
			phone: '',
			password: '',
			passwordEM: '',
			isLoading: false,

			countryPickerVisible: false,
			countryCode: "86",
			contryCodeLabel: `中国大陆 +86`
		}
	}


	UNSAFE_componentWillMount() {

	}

	componentDidMount() {

	}

	// 设置token
	async setToken(name, val) {
		try {
			await AsyncStorage.setItem(name, val);
		} catch (error) {
			// Error retrieving data
		}
	}

	// 登录
	async loginFunc() {
		let { phone, password } = this.state;

		let phoneMsg = ParamsValidate('phone', phone);
		if (phoneMsg !== null) {
			Toast.show({
				text: phoneMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return;
		}

		let passwordMsg = ParamsValidate('password', password);
		if (passwordMsg !== null) {
			Toast.show({
				text: passwordMsg,
				position: "top",
				textStyle: { textAlign: "center" },
				type: "warning"
			})
			return false;
		}

		this.setState({ isLoading: true })
		Http('post', "/user/login", {
			phone: this.state.phone,
			password: this.state.password
		}).then(res => {
			this.setState({ isLoading: false })
			if (res.code === 200) {
				this.setToken("globalInfo", JSON.stringify({ token: res.data.token }));
				this.props.loginSuccess(res.data);
				this.props.navigation.navigate('Users');
				// Toast.show({ text: "登录成功！", textStyle: { textAlign: "center" }, type: "success" });
			}
		})
	}

	render() {
		return (
			<Container>
				<Header title="登录" rightText="注册" onLeftPress={() => this.props.navigation.goBack()} onRightPress={() => this.props.navigation.navigate('Register')} />
				<Loading showLoading={this.state.isLoading} />
				<Content padder>
					<View style={Styles.showWelcome}>
						<Text style={Styles.showWelcomeText}> 欢迎来到 </Text>
						<Text style={Styles.showWelcomeText}> 拾柴聚火 </Text>
					</View>

					<TextInput
						inputStyle={Styles.inputText}
						placeholder='请输入手机号'
						keyboardType='phone-pad'
						// errorMessage='请输入正确的手机号码'
						value={this.state.phone}
						onChangeText={(value) => this.setState({ phone: value })}
					/>

					<TextInput
						inputStyle={Styles.inputText}
						placeholder="请输入密码"
						errorMessage={this.state.passwordEM}
						secureTextEntry={true}
						onChangeText={(value) => this.setState({ password: value })}
					/>

					<View style={Styles.signInView}>
						<TouchableOpacity onPress={() => this.loginFunc()} disabled={this.state.isLoading}>
							<LinearGradient style={{ width: Metrics.screenWidth * 0.6, alignItems: "center", borderRadius: 8 }} colors={[Colors.subjectJbZuo, Colors.subject]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}>
								<Text style={{ fontSize: 14, padding: 12, color: Colors.bai }}>{`${this.state.isLoading ? "登录中..." : "登 录"}`}</Text>
							</LinearGradient>
						</TouchableOpacity>
						<View style={Styles.resetPwd}>
							<TouchableOpacity onPress={() => this.props.navigation.navigate("ForgetPassword")}>
								<Text style={{ fontSize: 14, padding: 10, color: Colors.hui33 }}>忘记密码</Text>
							</TouchableOpacity>
						</View>
					</View>
					<Text style={Styles.yhXieyi}>
						登录/注册代表您已同意
						<Text onPress={() => this.props.navigation.navigate("ServiceAgreement")} style={Styles.yhXieyiText}> 用户协议 </Text>
						与
						<Text onPress={() => this.props.navigation.navigate("PrivacyPolicy")} style={Styles.yhXieyiText}> 用户隐私协议 </Text>
					</Text>
				</Content>
			</Container>
		);
	}

}

const mapStateToProps = state => ({
	logged: state.user.logged,
	token: state.user.token,

});

const mapDispatchToProps = dispatch => ({
	loginSuccess: userInfo => dispatch({ type: 'LoginSuccess', payload: { userInfo } }),
});

export default connect(mapStateToProps, mapDispatchToProps)(Login);

const Styles = StyleSheet.create({
	signInView: { marginTop: 58, alignItems: "center" },
	loginBtn: { width: Metrics.screenWidth * 0.6, alignItems: "center", borderRadius: 8 },
	resetPwd: { width: Metrics.screenWidth * 0.5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: 6 },
	inputText: { fontSize: 16, marginTop: 28, padding: 6, },
	showWelcome: { marginTop: 58, marginBottom: 28 },
	showWelcomeText: { textAlign: 'center', fontSize: 26 },
	yhXieyi: { fontSize: 12, color: Colors.hui99, textAlign: 'center', marginTop: 88 },
	yhXieyiText: { fontSize: 12, color: Colors.hui33, }
});